package com.yangweiqiao.fastindex;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Created by yangweiqiao on 2016/8/21.
 */
public class HanYuPinYinUtil {


    public static String chineseWordToPinyin(String chineseWord) {
        HanyuPinyinOutputFormat  format =null;
        //初始化汉语拼音格式化类
        if (format == null) {
            format = new HanyuPinyinOutputFormat();
        }
        //设置大写
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        //设置去除声调
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //定义StringBuilder用于拼接字符串
        StringBuilder sb = new StringBuilder();
        char[] charArray = chineseWord.toCharArray();
        for (char c : charArray) {
            //如果发现空格,则跨过
            if (Character.isWhitespace(c)) {
                continue;
            }
            //如果是中文字,则转换为拼音
            if (Character.toString(c).matches("[\\u4E00-\\u9FA5]")) {
                try {
                    String result = PinyinHelper.toHanyuPinyinStringArray(c, format)[0];
                    sb.append(result);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                //如果是普通字母,则转换为大写并拼接
                if (Character.isLetter(c)) {
                    sb.append(Character.toUpperCase(c));
                } else {
                    //其他特殊字符,转换为"#"
                    sb.append("#");
                }
            }
        }
        return sb.toString();

    }
}
